//
//  GaragelistViewController.m
//  KEREN
//
//  Created by MW on 2023/4/11.
//

#import "GaragelistViewController.h"
#import "DeviceTimeCell.h"
#import "DeviceShareVC.h"
@interface GaragelistViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, assign) int currentIndex;
@property (nonatomic, strong) DeviceInfo *deviceInfo;
@end

@implementation GaragelistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}


- (void)getDeviceList{
    [self setNavViewWithRightTitle:@"保存" navColorIswhite:YES withTitle:@"车辆选择"];
    _deviceInfo = [[UserInfoManager sharedInstance] currentDeviceInfo];
    if(!_deviceInfo){
        if([UserInfoManager sharedInstance].deviceInfoList.count > 0){
            _deviceInfo = [UserInfoManager sharedInstance].deviceInfoList.lastObject;
        }
    }
    WEAKSELF
    self.rightClickBlock = ^(void){
        [[NSNotificationCenter defaultCenter] postNotificationName:CHOOSEDEVICE object:weakSelf.deviceInfo];

        [weakSelf.navigationController popViewControllerAnimated:YES];
        //User_update
    };
    [NetworkingTool POST:Device_list parameters:@{} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if(response[@"data"] && [response[@"data"] isKindOfClass:[NSArray class]]){
            [weakSelf.deviceInfoList removeAllObjects];
            NSArray *dataArr = response[@"data"];
            for (int i = 0; i < dataArr.count; i++) {
                NSDictionary *dict = dataArr[i];
                DeviceInfo *deviceInfo = [DeviceInfo initWithDictionary:dict];
                [weakSelf.deviceInfoList addObject:deviceInfo];
                if(deviceInfo.is_manager){
                    [weakSelf.devicesArrM addObject:deviceInfo];
                }
            }
            [UserInfoManager sharedInstance].deviceInfoList = weakSelf.deviceInfoList;
            weakSelf.tableView.frame = CGRectMake(0, 66 + STATUSBAR_HEIGHT, DEVICE_WIDTH, DEVICE_HEIGHT- STATUSBAR_HEIGHT - 66);
            [weakSelf.tableView reloadData];
        }

    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];

}

- (void)requsetDeviceInfoList{
    _deviceInfo = [[UserInfoManager sharedInstance] currentDeviceInfo];
    if(!_deviceInfo){
        if([UserInfoManager sharedInstance].deviceInfoList.count > 0){
            _deviceInfo = [UserInfoManager sharedInstance].deviceInfoList.lastObject;
        }
    }
    WEAKSELF
    [NetworkingTool POST:Device_list parameters:@{} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if(response[@"data"] && [response[@"data"] isKindOfClass:[NSArray class]]){
            [weakSelf.deviceInfoList removeAllObjects];
            [weakSelf.devicesArrM  removeAllObjects];
            NSArray *dataArr = response[@"data"];
            for (int i = 0; i < dataArr.count; i++) {
                NSDictionary *dict = dataArr[i];
                DeviceInfo *deviceInfo = [DeviceInfo initWithDictionary:dict];
                [weakSelf.deviceInfoList addObject:deviceInfo];
            }
          //  [UserInfoManager sharedInstance].deviceInfoList = weakSelf.deviceInfoList;
            if(weakSelf.deviceInfoList.count > 0){
                self.tableView.tableHeaderView = [self headerView];
                self.devicesArrM = weakSelf.deviceInfoList;
                for (DeviceInfo *device in self.devicesArrM) {
                    if (device.Id == self.deviceInfo.Id){
                        [self.devicesArrM removeObject:device];
                        break;
                    }
                }
            }
            if([UserInfoManager sharedInstance].deviceInfoList.count == 0){
                weakSelf.tableView.tableHeaderView = [[KRNodataView alloc] initWithFrame:CGRectZero];
            }
            [weakSelf.tableView reloadData];
        }else{
            [weakSelf.devicesArrM removeAllObjects];
            weakSelf.tableView.tableHeaderView = [[KRNodataView alloc] initWithFrame:CGRectZero];
        }

    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)getDevicesharelist{
    WEAKSELF
    NSDictionary *parameters = @{@"type":@(1)};
    [NetworkingTool POST:Device_share_list parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if(response[@"data"][@"list"] && [response[@"data"][@"list"] isKindOfClass:[NSArray class]]){
                [weakSelf.devicesArrM removeAllObjects];
                NSArray *arr = response[@"data"][@"list"];
                for (int i = 0; i < arr.count; i ++) {
                    NSDictionary *dict = arr[i];
                    [weakSelf.devicesArrM addObject:dict];
                }
                if(weakSelf.devicesArrM.count == 0){
                    weakSelf.tableView.tableHeaderView = [[KRNodataView alloc] initWithFrame:CGRectZero];
                }else{
                    weakSelf.tableView.tableHeaderView = nil;
                }
                [weakSelf.tableView reloadData];
            }else{
                [weakSelf.devicesArrM removeAllObjects];
                weakSelf.tableView.tableHeaderView = [[KRNodataView alloc] initWithFrame:CGRectZero];
                [weakSelf.tableView reloadData];
            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        if(weakSelf.devicesArrM.count == 0){
            [weakSelf.devicesArrM removeAllObjects];
            weakSelf.tableView.tableHeaderView = [[KRNodataView alloc] initWithFrame:CGRectZero];
        }else{
            weakSelf.tableView.tableHeaderView = nil;
        }
    }];
}

- (void)getDeviceUserShareList{
    WEAKSELF
    [NetworkingTool POST:Device_user_share_list parameters:@{} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            [self.devicesArrM removeAllObjects];
            if(response[@"data"][@"list"] && [response[@"data"][@"list"] isKindOfClass:[NSArray class]]){
                NSArray *arr = response[@"data"][@"list"];
                for (int i = 0; i < arr.count; i++) {
                    NSDictionary *dict = arr[i];
                    [weakSelf.devicesArrM addObject:dict];
                }
                if(weakSelf.devicesArrM.count == 0){
                    weakSelf.tableView.tableHeaderView = [[KRNodataView alloc] initWithFrame:CGRectZero];
                }else{
                    weakSelf.tableView.tableHeaderView = nil;
                }
                [weakSelf.tableView reloadData];
            }else{
                weakSelf.tableView.tableHeaderView = [[KRNodataView alloc] initWithFrame:CGRectZero];
                [weakSelf.tableView reloadData];

            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        if(self.devicesArrM.count == 0){
            self.tableView.tableHeaderView = [[KRNodataView alloc] initWithFrame:CGRectZero];
        }else{
            self.tableView.tableHeaderView = nil;
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.devicesArrM.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [UIView new];
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return .01f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [UIView new];
    headView.backgroundColor = [UIColor clearColor];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DeviceTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DeviceTimeCell"];
    cell.countLbl.hidden = YES;
    cell.shareBtn.hidden = YES;
    cell.rightIcon.hidden = YES;
    cell.shareName.hidden = YES;
    cell.widthConstraint.constant = 60;
    cell.nameLblTop.constant = 25;
    if(_type == 1001 && _deviceInfo == self.devicesArrM[indexPath.section]){
        cell.layer.borderColor = Color_7ACC00.CGColor;
        cell.layer.borderWidth = 1;
    }else{
        cell.layer.borderWidth = 0;
    }
    if([self.devicesArrM[indexPath.section] isKindOfClass:[DeviceInfo class]]){
        DeviceInfo *info = self.devicesArrM[indexPath.section];
        [cell.deviceIcon sd_setImageWithURL:[NSURL URLWithString:info.photo] placeholderImage:[UIImage imageNamed:@"devcie_defalaut_icon"] options:SDWebImageRefreshCached];
        cell.nameLbl.text = info.name;
        cell.timeLbl.text = [[DeteManager shareInstance] timeFormatted:[info.created_at intValue]];
    }else{
        NSDictionary *dict = self.devicesArrM[indexPath.section];
        cell.nameLbl.text = dict[@"name"];
        cell.timeLbl.text = [[DeteManager shareInstance] timeFormatted:[dict[@"created_at"] intValue]];
        NSString *photo = dict[@"photo"];
        if(![dict[@"photo"] hasPrefix:@"http"]){
            photo = [NSString stringWithFormat:@"%@%@",BaseimageUrl,photo];
        }
        photo = [photo stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [cell.deviceIcon sd_setImageWithURL:[NSURL URLWithString:photo] placeholderImage:[UIImage imageNamed:@"devcie_defalaut_icon"]];

        cell.countLbl.hidden = NO;
        if(dict[@"list"] && [dict[@"list"] isKindOfClass:[NSArray class]]){
            NSArray *list = dict[@"list"];
            cell.countLbl.text = [NSString stringWithFormat:@"%ld人",list.count];
            cell.shareName.hidden = YES;
            cell.rightIcon.hidden = NO;
        }else{
            cell.countLbl.hidden = YES;
            cell.shareName.hidden = NO;
            if([dict[@"status"] intValue] == 1){
                cell.shareBtn.hidden = NO;
                cell.widthConstraint.constant = 110;
            }else{
                cell.shareBtn.hidden = YES;
            }
            cell.shareName.text = [NSString stringWithFormat:@"   分享人：%@   ",dict[@"user_name"]];
            cell.shareName.layer.cornerRadius = 7;
            cell.shareName.clipsToBounds = YES;
            cell.shareName.layer.borderWidth = 1;
            cell.shareName.layer.borderColor = Color_7ACC00.CGColor;
            cell.shareBtn.layer.cornerRadius = 18;
            cell.shareBtn.clipsToBounds = YES;
            cell.shareBtn.tag = indexPath.section;
            cell.nameLblTop.constant = 35;
            [cell.shareBtn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            
            if([dict[@"share_time"] intValue] > 10 && [dict[@"status"] intValue] != 1){
                cell.timeLbl.text = [NSString stringWithFormat:@"到期时间：%@",[[DeteManager shareInstance] timeFormatted:([dict[@"accepted_at"] intValue]+[dict[@"share_time"] intValue])]];
            }else{
                cell.timeLbl.text = [[DeteManager shareInstance] timeFormatted:[dict[@"created_at"] intValue]];
            }
        }
        
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSDictionary *dict = self.devicesArrM[indexPath.section];
    if(_type == 1001){
        _deviceInfo = self.devicesArrM[indexPath.section];
        [self.tableView reloadData];
    }
    if([self.devicesArrM[indexPath.row] isKindOfClass:[DeviceInfo class]]){
        return;
    }
    if(dict[@"list"] && [dict[@"list"] isKindOfClass:[NSArray class]]){
        DeviceInfo *info = [DeviceInfo initWithDictionary:dict];
        DeviceShareVC *vc = [[DeviceShareVC alloc] init];
        vc.deviceInfo = info;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)shareBtnClick:(UIButton *)button{
    WEAKSELF
    [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
    NSDictionary *dict = self.devicesArrM[button.tag];
    NSDictionary *parameters = @{@"id":dict[@"id"]};
    [NetworkingTool POST:Device_share_accept parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        [[KRAlartManager shareInstance] hidenAlartView];
        if([response[@"code"] intValue] == 0){
            weakSelf.tabBarController.selectedIndex = 0;
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        }else{
            //[[KRAlartManager shareInstance] showErrorAlert:response[@"msg"]];
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT - NAVTOP_Height)];
        _tableView.backgroundColor = Main_BackColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 108;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"DeviceTimeCell" bundle:nil] forCellReuseIdentifier:@"DeviceTimeCell"];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)devicesArrM{
    if(!_devicesArrM){
        _devicesArrM = [NSMutableArray array];
    }
    return _devicesArrM;
}

- (UIView *)headerView{
    if(!_headerView){
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_WIDTH - 248 + 85)];
        _headerView.backgroundColor = [UIColor clearColor];
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(24, 10, DEVICE_WIDTH - 48, DEVICE_WIDTH - 248 + 75)];
        backView.backgroundColor = Whire_Color;
        [_headerView addSubview:backView];
        backView.layer.cornerRadius = 25;
        backView.clipsToBounds = YES;
        backView.layer.borderColor = Color_7ACC00.CGColor;
        backView.layer.borderWidth = 1;
        
        UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(100, 0, DEVICE_WIDTH - 248, DEVICE_WIDTH - 248)];
        DeviceInfo *currentInfo = _deviceInfo;
        [icon sd_setImageWithURL:[NSURL URLWithString:currentInfo.photo] placeholderImage:[UIImage imageNamed:@"devcie_defalaut_icon"] options:SDWebImageRefreshCached];
        UILabel *nameLbl = [UILabel setLblText:currentInfo.name font:Font(24) withColor:Black_Color inSubView:backView];
        [nameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(backView);
            make.top.offset(DEVICE_WIDTH - 248);
            make.height.offset(34);
        }];
        UILabel *timelbl = [UILabel setLblText:[[DeteManager shareInstance] timeFormatted:[currentInfo.created_at intValue]] font:Font(12) withColor:Color_86898E inSubView:backView];
        [timelbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.offset(-20);
            make.centerX.equalTo(backView);
        }];
        [backView addSubview:icon];
        
        UILabel *tipsLbl = [UILabel setLblText:@"使用中" font:BFont(12) withColor:Whire_Color inSubView:backView];
        tipsLbl.frame = CGRectMake(DEVICE_WIDTH - 48 - 72, 0, 72, 25);
        tipsLbl.backgroundColor = Color_7ACC00;
        tipsLbl.textAlignment = NSTextAlignmentCenter;
        tipsLbl.layer.mask = [CAShapeLayer clipsToBounds:CGRectMake(0, 0, 72, 25) Corners:UIRectCornerBottomLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(25, 25)];
    }
    return _headerView;
}

@end
